/*
 * samaxesJS.document namespace offers utility methods to other controls under
 * the same namespace.
 */
samaxesJS.document = {
    createLink: function(href, innerHTML) {
        var a = document.createElement("a");
        a.setAttribute("href", href);
        a.innerHTML = innerHTML;
        return a;
    }
};

/*
 * The TOC control dynamically builds a table of contents from the headings in
 * a document and prepends legal-style section numbers to each of the headings.
 */
samaxesJS.document.TOC = {
    create: function(toc) {
        var i2 = 0, i3 = 0, i4 = 0;
        var nodes = document.body.childNodes;
        toc = toc.appendChild(document.createElement("ul"));
        for (var i = 0; i < nodes.length; ++i) {
            var node = nodes[i];
            var tagName = node.nodeName.toLowerCase();
            var section;
            if (tagName == "h4") {
                ++i4;
                if (i4 == 1) {
                    toc.lastChild.lastChild.lastChild.appendChild(document.createElement("ul"));
                }
                section = i2 + "." + i3 + "." + i4;
                node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
                toc.lastChild.lastChild.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(
                    samaxesJS.document.createLink("#" + node.id, node.innerHTML));
            } else if (tagName == "h3") {
                ++i3; i4 = 0;
                if (i3 == 1) {
                    toc.lastChild.appendChild(document.createElement("ul"));
                }
                section = i2 + "." + i3;
                node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
                toc.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(
                    samaxesJS.document.createLink("#" + node.id, node.innerHTML));
            } else if (tagName == "h2") {
                ++i2; i3 = 0; i4 = 0;
                section = i2;
                node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
                toc.appendChild(document.createElement("li")).appendChild(
                    samaxesJS.document.createLink("#" + node.id, node.innerHTML));
            }
        }
    }
};
